<script setup>
import { ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import { useUserInfoStore } from '@/stores/userInfo';
import { updatePassword } from '@/api/user';
import { useRouter } from 'vue-router';

const userInfoStore = useUserInfoStore();
const router = useRouter();

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});

const formRef = ref(null);

const rules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value) => value === passwordForm.value.newPassword,
      message: '两次输入密码不一致',
      trigger: 'blur'
    }
  ]
};

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updatePassword({
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword
        });
        ElMessage.success('密码更新成功');
        userInfoStore.logout();
        router.push('/login');
      } catch (error) {
        ElMessage.error('密码更新失败');
      }
    }
  });
};
</script>

<template>
  <el-card class="reset-password-container">
    <template #header>
      <div class="card-header">
        <h3>重置密码</h3>
      </div>
    </template>

    <el-form
        ref="formRef"
        :model="passwordForm"
        :rules="rules"
        label-width="120px"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmNewPassword">
        <el-input
            v-model="passwordForm.confirmNewPassword"
            type="password"
            placeholder="请再次输入新密码"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">更新密码</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped>
.reset-password-container {
  padding: 20px;
  max-width: 500px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
}
</style>